package com.glut.campusrepair.controller;

import com.glut.campusrepair.entity.RepairPersonnel1;
import com.glut.campusrepair.entity.RepairTaskAssignmentDTO;
import com.glut.campusrepair.entity.RepairTasks1;
import com.glut.campusrepair.service.IRepairPersonnel1Service;
import com.glut.campusrepair.service.IRepairTasks1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/**
 * RepairTasks1Controller 是用于处理维修任务的 RESTful 控制器
 */
@RestController
@RequestMapping("/repair-tasks1")
public class RepairTasks1Controller {

    @Autowired
    private IRepairTasks1Service repairTasks1Service;
    @Autowired
    private IRepairPersonnel1Service repairPersonnel1Service; // 添加

    /**
     * 创建新的维修任务
     *
     * @param task 维修任务实体
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<String> createTask(@RequestBody RepairTasks1 task) {
        // 检查是否已经存在任务
        boolean taskExists = repairTasks1Service.existsByFailureRepairId(task.getFailureRepairId());
        if (taskExists) {
            return ResponseEntity.status(400).body("该报修单已存在任务");
        }

        // 设置当前时间为任务分配时间
        task.setAssignedTime(new Timestamp(System.currentTimeMillis()));

        // 设置默认的任务状态为 '待接受'
        if (task.getStatus() == null || task.getStatus().isEmpty()) {
            task.setStatus("待接受");
        }

        boolean saved = repairTasks1Service.save(task);
        if (saved) {
            return ResponseEntity.ok("任务创建成功");
        }
        return ResponseEntity.status(500).body("任务创建失败");
    }

    /**
     * 检查报修单是否已存在任务
     *
     * @param failureRepairId 故障报修ID
     * @return 任务存在性结果
     */
    @GetMapping("/exists/{failureRepairId}")
    public ResponseEntity<Boolean> checkIfTaskExists(@PathVariable int failureRepairId) {
        boolean exists = repairTasks1Service.existsByFailureRepairId(failureRepairId);
        return ResponseEntity.ok(exists);
    }

    /**
     * 获取维修人员与报修任务的分配数据
     *
     * @return 维修人员与报修任务的分配数据列表
     */
    @GetMapping("/assignments")
    public ResponseEntity<List<RepairTaskAssignmentDTO>> getAssignments() {
        List<RepairTasks1> tasks = repairTasks1Service.list();
        List<RepairPersonnel1> personnelList = repairPersonnel1Service.list();

        List<RepairTaskAssignmentDTO> assignments = tasks.stream()
                .map(task -> {
                    RepairPersonnel1 personnel = personnelList.stream()
                            .filter(p -> p.getRepairPersonnelId().equals(task.getRepairPersonnelId()))
                            .findFirst()
                            .orElse(null);

                    // 转换 java.util.Date 为 java.sql.Timestamp
                    Timestamp assignedTime = (task.getAssignedTime() instanceof Timestamp) ?
                            (Timestamp) task.getAssignedTime() :
                            new Timestamp(((java.util.Date) task.getAssignedTime()).getTime());

                    return new RepairTaskAssignmentDTO(
                            task.getTaskId(),
                            task.getFailureRepairId(),
                            task.getRepairPersonnelId(),
                            personnel != null ? personnel.getFullName() : "未知",
                            personnel != null ? personnel.getMaintenanceType() : "未知",
                            assignedTime
                    );
                })
                .collect(Collectors.toList());

        return ResponseEntity.ok(assignments);
    }

    /**
     * 删除任务
     *
     * @param taskId 任务ID
     * @return 删除结果
     */
    @DeleteMapping("/{taskId}")
    public ResponseEntity<String> deleteTask(@PathVariable int taskId) {
        boolean deleted = repairTasks1Service.removeById(taskId);
        if (deleted) {
            return ResponseEntity.ok("任务删除成功");
        }
        return ResponseEntity.status(500).body("任务删除失败");
    }
}
